package com.gz.thread.lock;

import java.util.concurrent.locks.ReentrantLock;

public class ThreadLock {

    public static void main(String[] args) {
        BuyTricksLock buyTricks = new BuyTricksLock();
        new Thread(buyTricks).start();
        new Thread(buyTricks).start();
        new Thread(buyTricks).start();
    }
}


class BuyTricks implements Runnable {

    public int trickNum = 10;

    public void run() {
        while (true) {
            if (trickNum <= 0) {
                break;
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(trickNum--);
        }

    }
}

class BuyTricksSync implements Runnable {

    public Integer trickNum = 10;

    public void run() {

        synchronized (trickNum) {
            while (true) {
                if (trickNum <= 0) {
                    break;
                }
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(trickNum--);
            }
        }
    }
}


class BuyTricksLock implements Runnable {

    public Integer trickNum = 10;
   public ReentrantLock lock = new ReentrantLock();
    public void run() {

        while (true) {
            try {
                lock.lock();
                if (trickNum <= 0) {
                    break;
                }
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(trickNum--);
            }finally {
                lock.unlock();
            }
        }
    }
}